<template>
  <div class="app-container v-flex">
    <filter-form :form="listQuery" :data="filterData" @search="search" @addForm="addForm" />
    <div ref="main" class="v-flex-elastic">
      <el-table
        v-if="height>0"
        ref="multipleTable"
        v-loading="listLoading"
        :data="tableData"
        border
        :height="height"
        tooltip-effect="dark"
        style="width: 100%">
        <el-table-column label="序号" align="center" type="index" width="50" />
        <el-table-column prop="appName" show-overflow-tooltip label="应用名称" />
        <el-table-column prop="clientId" show-overflow-tooltip label="客户端ID" />
        <el-table-column prop="scope" show-overflow-tooltip label="授权范围" />
        <el-table-column prop="authorizedGrantTypes" show-overflow-tooltip label="授权类型" />
        <el-table-column prop="webServerRedirectUri" min-width="95px" show-overflow-tooltip label="重定向地址" />
        <el-table-column prop="accessTokenValidity" min-width="115px" show-overflow-tooltip label="请求token验证" />
        <el-table-column prop="refreshTokenValidity" min-width="115px" show-overflow-tooltip label="刷新token验证" />
        <el-table-column prop="clientPassword" show-overflow-tooltip label="密码" />
        <el-table-column prop="flowStatusText" show-overflow-tooltip label="状态" />
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          width="250"
          class-name="small-padding fixed-width">
          <template slot-scope="{row ,$index}">
            <el-button
              v-permission-button="'ITPS-VIEW'"
              class="el-icon-defined"
              size="mini"
              icon="el-icon-view"
              @click="view(row)" />
            <!-- <el-button
              class="el-icon-defined"
              size="mini"
              icon="el-icon-setting"
              title="修改密码"
              @click="changePwd(row,$index)" /> -->
            <el-button
              v-permission-button="'ITPS-UPDATE'"
              class="el-icon-defined"
              size="mini"
              icon="el-icon-edit"
              @click="updateForm(row,$index)" />
            <el-button
              v-permission-button="'ITPS-DELETE'"
              class="el-icon-defined"
              size="mini"
              icon="el-icon-delete"
              @click="deleteData(row,$index)" />
            <el-button
              v-if="row.flowStatus!==1"
              size="mini"
              class="td-btn-operation"
              @click="audit(row,$index)">审核</el-button>
            <el-button
              size="mini"
              class="td-btn-operation"
              @click="changePwd(row,$index)">修改密码</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <base-dialog
      class="client-plan-dialog"
      :visible.sync="dialogFormVisible"
      :title="textMap[dialogStatus]"
      :loading="loading"
      :disabled="disabled"
      @updateData="dialogStatus==='create'?addData():updateData()">
      <el-form ref="dataForm" :rules="rules" :model="temp" :disabled="disabled" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属应用" prop="appId">
              <el-select v-model="temp.appId" class="filter-item">
                <el-option
                  v-for="item in appList"
                  :key="item.id"
                  :label="item.appName"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户端ID" prop="clientId">
              <el-input v-model="temp.clientId" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="授权范围" prop="scope">
              <el-input v-model="temp.scope" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="授权类型" prop="authorizedGrantTypes">
              <el-select
                v-model="authorizedGrantTypes"
                class="filter-item"
                multiple
                collapse-tags
                @change="changeType">
                <el-option label="authorization_code" value="authorization_code" />
                <el-option label="client_credentials" value="client_credentials" />
                <el-option label="password" value="password" />
                <el-option label="refresh_token" value="refresh_token" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="客户端跳转地址" prop="webServerRedirectUri">
              <el-input v-model="temp.webServerRedirectUri" type="textarea" :rows="4" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="请求token验证" prop="accessTokenValidity">
              <el-input v-model.number="temp.accessTokenValidity" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="刷新token验证" prop="refreshTokenValidity">
              <el-input v-model.number="temp.refreshTokenValidity" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </base-dialog>
    <base-dialog
      class="client-plan-dialo"
      :visible.sync="pwdVisible"
      title="修改密码"
      :loading="loading"
      @updateData="updatePwd">
      <el-form ref="dateForm1" :model="pwdModal" :rules="pwdRules" label-width="100px">
        <el-form-item label="注意">
          <span style="color:red;">修改完成后，请重启认证服务中心！！！</span>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="pwdModal.password" clearable />
        </el-form-item>
        <el-form-item label="确认密码" prop="rePassword">
          <el-input v-model="pwdModal.rePassword" clearable />
        </el-form-item>
      </el-form>
    </base-dialog>
  </div>
</template>

<script>
import {
  getList,
  saveOrUpdate,
  audit,
  deleteById,
  updatePwd
} from '@/api/dsc/interface/client-plan'
import { getAppList } from '@/api/dsc/system/application'
import { tableMixin } from '@/utils/public'
export default {
  name: 'DscClientPlan',
  mixins: [tableMixin],
  data() {
    const validPwd = (rule, value, callback) => {
      const reg = /[\u4e00-\u9fa5]+/
      if (reg.test(this.pwdModal.password)) {
        callback(new Error('密码不能有中文'))
      }
      callback()
    }
    const validRePwd = (rule, value, callback) => {
      if (this.pwdModal.password !== this.pwdModal.rePassword) {
        callback(new Error('两次密码输入不一致'))
      }
      callback()
    }
    return {
      height: 0, // table高度
      tableData: [], // 表格数据
      listQuery: {
        // 搜索条件
        appId: ''
      },
      filterData: {
        appId: {
          key: 'appId',
          type: 'select',
          title: '所属应用',
          placeholder: '所有应用',
          options: [],
          props: { label: 'appName', value: 'id' }
        }
      },
      appList: [], // 所属应用
      total: 0,
      textMap: {
        update: '编辑',
        view: '查看',
        create: '添加'
      },
      dialogFormVisible: false, // 弹窗开关
      dialogStatus: '', // 弹窗类型（添加、查看、编辑）
      loading: false,
      temp: {},
      tempForm: {
        // 弹窗表单
        id: null,
        appId: '',
        clientId: '',
        scope: '',
        authorizedGrantTypes: '',
        webServerRedirectUri: '',
        accessTokenValidity: '',
        refreshTokenValidity: ''
      },
      rowIndex: null,
      authorizedGrantTypes: [], // 选择的权限类型
      rules: {},
      rulesModel: {
        appId: [{ required: true, message: '必填', trigger: 'blur' }],
        clientId: [
          { required: true, message: '必填', trigger: 'blur' },
          { max: 255, message: '小于255个字符', trigger: 'blur' }
        ],
        scope: [{ max: 255, message: '小于255个字符', trigger: 'blur' }],
        authorizedGrantTypes: [
          { required: true, message: '必填', trigger: 'blur' }
        ],
        webServerRedirectUri: [
          // { required: true, message: '必填', trigger: 'blur' },
          { max: 2000, message: '小于2000个字符', trigger: 'blur' }
        ],
        accessTokenValidity: [
          { required: true, message: '必填', trigger: 'blur' },
          { type: 'number', message: '输入数字', trigger: 'blur' }
        ],
        refreshTokenValidity: [
          { required: true, message: '必填', trigger: 'blur' },
          { type: 'number', message: '输入数字', trigger: 'blur' }
        ]
      },
      listLoading: false,
      disabled: false, // 是否禁止表单操作
      pwdVisible: false,
      pwdModal: {
        id: '',
        password: '',
        rePassword: ''
      },
      pwdRules: {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validPwd, trigger: 'blur' }
        ],
        rePassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validRePwd, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.temp = Object.assign({}, this.tempForm)
    getAppList({}).then(response => {
      this.appList = response.data
      this.filterData['appId'].options = response.data
    })
    this.getList()
  },
  methods: {
    changeType(data) {
      this.temp.authorizedGrantTypes = this.authorizedGrantTypes.join(',')
    },
    // 查询列表
    getList() {
      this.listLoading = true
      getList(this.listQuery)
        .then(response => {
          this.tableData = response.data
          this.listLoading = false
        })
        .catch(_ => {
          this.listLoading = false
        })
    },
    // 搜索
    search() {
      this.getList()
    },
    // 添加
    addForm() {
      this.disabled = false
      this.temp = Object.assign({}, this.tempForm)
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.authorizedGrantTypes = []
      this.rules = Object.assign({}, this.rulesModel)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 添加数据
    addData() {
      this.validate().then(() => {
        this.saveOrUpdate(this.temp, 1)
      })
    },
    // 查看
    view(row) {
      this.disabled = true
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'view'
      this.rules = {}
      this.dialogFormVisible = true
    },
    // 编辑
    updateForm(row, $index) {
      this.disabled = false
      this.rowIndex = $index
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.rules = Object.assign({}, this.rulesModel)
      const authorizedGrantTypes = this.temp.authorizedGrantTypes
      this.authorizedGrantTypes = authorizedGrantTypes.split(',')
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑数据
    updateData() {
      this.validate().then(() => {
        this.saveOrUpdate(this.temp, 2)
      })
    },
    // type 1 添加，2 编辑
    saveOrUpdate(params, type) {
      this.loading = true
      const param = Object.assign({}, params)
      saveOrUpdate(param)
        .then(response => {
          if (type === 1) {
            this.tableData.unshift(response.data)
            this.total++
          } else {
            Object.assign(this.tableData[this.rowIndex], response.data)
          }
          this.notifiySuccess('保存成功!')
          this.dialogFormVisible = false
          this.loading = false
        })
        .catch(_ => {
          this.loading = false
        })
    },
    // 删除
    deleteData(row, $index) {
      this.confirmBox('确定删除?')
        .then(() => {
          deleteById(row.id).then(response => {
            this.notifiySuccess('删除成功!')
            // this.tableData.splice($index, 1)
            // this.total--
            this.getList()
          })
        })
        .catch(() => {})
    },
    // 审核
    audit(row, $index) {
      this.confirmBox('审核通过?')
        .then(() => {
          audit({ id: row.id }).then(response => {
            this.notifiySuccess('审核通过!')
            Object.assign(this.tableData[$index], response.data)
          })
        })
        .catch(() => {})
    },
    changePwd(row, index) {
      this.rowIndex = index
      this.pwdVisible = true
      this.pwdModal.id = row.id
      this.$nextTick(_ => {
        this.pwdModal.password = this.pwdModal.rePassword = ''
        this.$refs.dateForm1.clearValidate()
      })
    },
    updatePwd() {
      this.$refs.dateForm1.validate(valid => {
        if (valid) {
          this.loading = true
          updatePwd(this.pwdModal)
            .then(response => {
              Object.assign(this.tableData[this.rowIndex], {
                clientPassword: response.data
              })
              this.loading = false
              this.pwdVisible = false
            })
            .catch(_ => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>
